package com.sky.aop;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.exception.BaseException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/*
自动填充AOP类
 */
@Component
@Aspect
public class AutoFillAspect {


    @Pointcut("@annotation(com.sky.annotation.AutoFill))")
    public void pt() {
    }

    @Before("pt()")
    public void before(JoinPoint joinPoint) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //已知这个方法 肯定有autofill
        Method method = signature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        //获取注解上配置的类型
        OperationType operationType = autoFill.value();
        //根据类型 做不同的设置
        //获取参数
        Object[] args = joinPoint.getArgs();
        Object o = args[0];
        Class<?> clazz = o.getClass();
        if (operationType == OperationType.INSERT) {  //新增 创建人 创建时间  更新人 更新时间
            //给参数设置值
            Method setCreateUser = clazz.getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            setCreateUser.invoke(o, BaseContext.getCurrentId());
            Method setCreateTime = clazz.getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            setCreateTime.invoke(o, LocalDateTime.now());
     /*       Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateUser.invoke(o, BaseContext.getCurrentId());
            Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(o, LocalDateTime.now());*/

        } /*else if (operationType == OperationType.UPDATE) { //修改  更新人 更新时间
            //给参数设置值
        }
*/
        Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
        setUpdateUser.invoke(o, BaseContext.getCurrentId());
        Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
        setUpdateTime.invoke(o, LocalDateTime.now());
    }


}
